import { createApp } from "vue";
import App from "./App.vue";

import "./style.scss";
import "uno.css";
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
import "element-plus/dist/index.css";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import { vLoadingFinish } from "./directives/loading";


// 2. 异步加载核心资源
async function bootstrapApp() {
  try {
    // 第一阶段：优先加载绝对必要资源
    const [{ createPinia }, { default: router }] = await Promise.all([
      import("pinia"),
      import("./router"), // 确保路由最先加载
    ]);
    // 第二阶段：创建基础Vue实例
    const app = createApp(App);
    app.use(createPinia());
    app.use(router);

    // 第三阶段：并行加载非关键资源
    const [{ default: ElementPlus }, { useThemeStore }] = await Promise.all([
      import("element-plus"),
      import("./stores/theme"),
    ]);

    app.use(ElementPlus, { locale: zhCn });

    // 5. 注册Element图标（同步加载）
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
      app.component(key, component);
    }

    // 6. 初始化主题
    const themeStore = useThemeStore();
    themeStore.initTheme();

    // 7. 注册自定义指令
    app.directive("loading-finish", vLoadingFinish);

    // 挂载前准备
    await new Promise((resolve) => setTimeout(resolve, 30)); // 确保至少显示30ms加载动画
    // 8. 挂载应用
    app.mount("#app");

    // 平滑移除loading
    removeLoading();
  } catch (error) {
    console.error("应用初始化失败:", error);
    handleLoadError(error);
  }
}
// 修改移除loading的逻辑
function removeLoading() {
  const loadingEl = document.getElementById("app-loading");
  if (!loadingEl) return;

  loadingEl.style.transition = "opacity 0.5s ease";
  loadingEl.style.opacity = "0";

  // 等待动画完成再移除
  loadingEl.addEventListener(
    "transitionend",
    () => {
      loadingEl.remove();
    },
    { once: true }
  );
}

function handleLoadError(error: any) {
  console.error(error);
  const loadingEl = document.getElementById("app-loading");
  if (loadingEl) {
    loadingEl.innerHTML = `
        <div style="text-align: center; padding: 20px;">
          <p style="color: red; margin-bottom: 10px;">加载失败</p>
          <button 
            style="padding: 5px 10px; background: #409EFF; color: white; border: none; border-radius: 4px;"
            onclick="window.location.reload()"
          >
            点击重试
          </button>
        </div>
      `;
  }
}
// 启动应用
bootstrapApp();
